﻿using System.Diagnostics;
/// <summary>
/// https://leetcode-cn.com/problems/3sum-closest/
/// </summary>
public class Solution
{
    public int ThreeSumClosest(int[] nums, int target)
    {
        int? min = null;
        var minDelta = int.MaxValue;

        Array.Sort(nums);

        for (int baseIndex = 0; baseIndex < nums.Length - 2; baseIndex++)
        {
            var baseValue = nums[baseIndex];

            int leftIndex = baseIndex + 1, rightIndex = nums.Length - 1;

            for (; leftIndex < rightIndex;)
            {
                var leftValue = nums[leftIndex];
                var rightValue = nums[rightIndex];
                int sum = baseValue + leftValue + rightValue;
                int delta = Math.Abs(target - sum);

                if (minDelta > delta)
                {
                    minDelta = delta;
                    min = sum;
                }

                if (sum == target)
                {
                    leftIndex++;
                    rightIndex--;
                }
                else if (sum < target)
                    leftIndex++;
                else // if (sum > target)
                    rightIndex--;
            }
        }

        Debug.Assert(min.HasValue);
        return min.Value;
    }
}